<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="单据Id" prop="headerId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.headerId"-->
      <!--          placeholder="请输入单据Id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="仓库" prop="depotId">
        <el-select v-model="queryParams.depotId" placeholder="请选择仓库" filterable clearable>
          <el-option
            v-for="item in allDepot1"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物品" prop="inventoryId">
        <el-select v-model="queryParams.inventoryId" placeholder="请选择物品" filterable clearable>
          <el-option
            v-for="item in allInventory"
            :key="item.id"
            :label="item.firstLetter + ' - '+ item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="锁定状态:0锁定1取消" prop="lockStatus">-->
      <!--        <el-select v-model="queryParams.lockStatus" placeholder="请选择锁定状态:0锁定1取消" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.ware_lock_status"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['warehouse:RyDepotItem:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport(0,'总库')"
          v-hasPermi="['system:user:import']"
        >上传总库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport(1,'工具库')"
          v-hasPermi="['system:user:import']"
        >上传工具库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['warehouse:RyDepotItem:export']"
        >导出
        </el-button>
      </el-col>
<!--      <el-col v-if="!uploadStatus" :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini"-->
<!--          @click="handleImportAll"-->
<!--          v-hasPermi="['warehouse:RyDepotItem:export']"-->
<!--        >上传总库-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col v-if="!uploadStatus" :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini"-->
<!--          @click="handleImportTool"-->
<!--          v-hasPermi="['warehouse:RyDepotItem:export']"-->
<!--        >上传工具库-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col v-if="uploadStatus" :span="1.5">-->
<!--        <el-upload-->
<!--          :on-change="uploadFile"-->
<!--          :auto-upload="false"-->
<!--          action=""-->
<!--          :show-file-list="false"-->
<!--          accept=".xls, .xlsx, .et"-->
<!--          :multiple="false">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="el-icon-upload2"-->
<!--            size="mini">导入库存-->
<!--          </el-button>-->
<!--        </el-upload>-->
<!--      </el-col>-->
<!--      <el-col v-if="uploadStatus" :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          @click="uploadStatus = false"-->
<!--          icon="el-icon-close"-->
<!--          size="mini">取消-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="RyDepotItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键" align="center" prop="id" />-->
      <!--      <el-table-column label="单据Id" align="center" prop="headerId" />-->

      <el-table-column label="仓库" align="center" prop="depotName"/>
      <!--      <el-table-column label="仓库ID" align="center" prop="depotId" />-->
      <el-table-column label="商品首字母" align="center" prop="firstLetter"/>
      <el-table-column label="商品" align="center" prop="inventoryName"/>
      <el-table-column label="规格" align="center" prop="specifications"/>
      <el-table-column label="项目名称" align="center" prop="projectName"/>
      <el-table-column label="项目编号" align="center" prop="projectCode"/>
      <!--      <el-table-column label="商品Id" align="center" prop="inventoryId" />-->
      <el-table-column label="入库数量" align="center" prop="operNumber"/>
      <el-table-column label="金额(元)" align="center" prop="allPrice"/>
      <el-table-column label="当前库存" align="center" prop="currentNumber"/>
      <el-table-column label="入库时间" align="center" prop="operTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="headerType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ware_depot_item_type" :value="scope.row.headerType"/>
        </template>
      </el-table-column>

      <el-table-column label="修改时间" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark"/>

      <!--      <el-table-column v-if="headerType!=null && headerType == '2'" label="锁定状态:0锁定1取消" align="center" prop="lockStatus">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.ware_lock_status" :value="scope.row.lockStatus"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouse:RyDepotItem:edit']"
          >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加入库对话框 -->
    <el-dialog ref="mydialog" :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!--        <el-form-item label="单据Id" prop="headerId">-->
        <!--          <el-input v-model="form.headerId" placeholder="请输入单据Id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="仓库" prop="depotId">
          <!--          <el-input v-model="form.depotId" placeholder="请输入仓库ID" />-->
          <el-select v-model="form.depotId" placeholder="请选择仓库" filterable>
            <el-option
              v-for="item in allDepot"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入库物品" prop="inventoryId">
          <!--          <el-input v-model="form.inventoryId" placeholder="请输入商品Id" />-->
          <el-select v-model="form.inventoryId" @change="onSelectedInventory" filterable placeholder="请选择入库物品">
            <el-option
              v-for="item in allInventory"
              :key="item.id"
              :label="item.firstLetter + ' - '+ item.label"
              :value="item.id"
            ></el-option>
          </el-select>
<!--          <el-button type="primary" style="margin-left: 20px">新增</el-button>-->
        </el-form-item>
        <el-form-item label="商品规格" prop="specifications">
          <el-input v-model="form.specifications" :disabled="true"/>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" :disabled="true"/>
        </el-form-item>
        <el-form-item label="wbs" prop="wbs">
          <el-input v-model="form.wbs" :disabled="true"/>
        </el-form-item>
        <el-form-item label="单价(元)" prop="unitPrice">
          <el-input v-model="form.unitPrice" :disabled="true"/>
        </el-form-item>
        <el-form-item label="入库数量" prop="operNumber">
          <el-input v-model.number="form.operNumber" placeholder="请输入数量" @blur="sumTotalPrice"/>
        </el-form-item>
        <el-form-item label="金额(元)" prop="allPrice">
          <el-input v-model="allPrice" :disabled="true"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <!--        <el-form-item label="锁定状态:0锁定1取消">-->
        <!--          <el-radio-group v-model="form.lockStatus">-->
        <!--            <el-radio-->
        <!--              v-for="dict in dict.type.ware_lock_status"-->
        <!--              :key="dict.value"-->
        <!--:label="dict.value"-->
        <!--            >{{dict.label}}</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    修改入库对话框-->
    <el-dialog ref="mydialog" :title="title" :visible.sync="modificationOpen" width="600px" append-to-body>
      <el-form ref="form1" :model="modificationform" label-width="120px">
        <el-form-item label="仓库">
          <el-input v-model.number="modificationform.depotName" disabled/>
        </el-form-item>
        <el-form-item label="入库物品">
          <el-input v-model.number="modificationform.inventoryName" disabled/>
        </el-form-item>
        <el-form-item label="入库数量">
          <el-input v-model.number="modificationform.operNumber" disabled/>
        </el-form-item>
        <el-form-item label="修改后入库数量">
          <el-input v-model.number="modificationform.afterNum" type="number" min="0"
                    onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
        </el-form-item>
        <el-form-item label="金额(元)">
          <el-input v-model="modificationform.allPrice" disabled=""/>
        </el-form-item>
        <el-form-item label="修改后金额(元)">
          <el-input v-model="modificationform.afterMoney"/>
        </el-form-item>
        <el-form-item label="入库时间">
          <el-date-picker clearable disabled
                          v-model="modificationform.operTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择入库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="modificationform.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="modificationSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :on-change="uploadFile"
        :auto-upload="false"
        :file-list="fileList"
        action=""
        :show-file-list="true"
        accept=".xls, .xlsx, .et"
        :multiple="false"
        :limit="1"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleImport1">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRyDepotItem,
  getRyDepotItem,
  delRyDepotItem,
  addRyDepotItem,
  updateRyDepotItem
} from "@/api/warehouse/RyDepotItem";
import {allRyDepot} from "@/api/warehouse/RyDepot";
import {allRyInventory, getInventoryInFor, getRyInventory} from "@/api/inventory/RyInventory";
import {floatAdd, floatSub, floatMul, floatDiv} from "@/utils/mathOperate";
import request from "../../../utils/request";
import {getToken} from "../../../utils/auth";

export default {
  name: "RyDepotItem",
  dicts: ['ware_depot_item_type', 'ware_lock_status'],
  data() {
    return {
      warehouseType: 0, // 仓库类型（0是总库1是工具库）
      uploadStatus: false, // 控制上传组件显隐
      allPrice: null,
      //所有仓库
      allDepot: [],
      allDepot1: [],
      //所有物品
      allInventory: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库表格数据
      RyDepotItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 修改弹出层
      modificationOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        headerId: null,
        inventoryId: null,
        depotId: null,
        lockStatus: null,
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 表单参数
      form: {},
      importData: [],
      // 修改表单
      modificationform: {},
      // 表单校验
      rules: {
        depotId: [
          {required: true, message: "仓库不能为空", trigger: "blur"}
        ],
        inventoryId: [
          {required: true, message: "商品不能为空", trigger: "blur"}
        ],
        operNumber: [
          {required: true, message: "入库数量不能为空", trigger: "blur"},
          {type: "number", message: "入库数量只能为数字类型", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    //查询仓库列表
    this.findAllRyDepot();
    this.allRyInventory();
  },
  // mounted(){
  //   this.$refs.mydialog.rendered=true;//让dialog不再懒加载
  //   this.$refs.form.rendered=true;//让dialog不再懒加载
  // },
  methods: {

    /**两数相乘*/
    sumTotalPrice() {
      console.log("SumTotalPrice");
      if (this.form.operNumber <= 0){
        this.form.operNumber = ''
        this.$modal.msgWarning('入库数量不能为0或负数')
      }
      if (this.form.operNumber && this.form.unitPrice) {
        // this.form.allPrice = this.form.operNumber * this.form.unitPrice;
        this.allPrice = floatMul(this.form.operNumber, this.form.unitPrice);
        this.form.allPrice = this.allPrice;

        // this.form = this.form;
        console.log(this.form.allPrice.toString());
        // alert("123");

      } else {
        this.form.allPrice = null;
        console.log("else");
      }
    },

    //根据物品编码查询物品信息
    onSelectedInventory(val) {
      console.log(val);
      getRyInventory(val).then(response => {
        let resultData = {
          depotId: this.form.depotId,
          inventoryId: this.form.inventoryId,
          remark: null,
          specifications: response.data.specifications,
          brand: response.data.brand,
          wbs: response.data.wbs,
          unitPrice: response.data.unitPrice,
        };
        // resultData.depotId = this.form.depotId;
        // resultData.inventoryId = this.form.inventoryId;
        // resultData.remark = null;
        this.form = resultData;
        // console.log(inventoryInfo);
        // this.form.specifications = response.data.specifications;
        // this.form.brand = response.data.brand;
        // this.form.wbs = response.data.wbs;
        // this.form.unitPrice = response.data.unitPrice;

      });
    },
    //查询仓库列表
    findAllRyDepot() {
      let that = this
      allRyDepot().then(response => {
        //需要将工具库移除

        for (let i = 0; i < response.data.length; i++) {
          if (response.data[i].type !== '2') {
            this.allDepot.push(response.data[i])
            console.log(that.allDepot)
          }
        }
        that.allDepot1 = response.data
      })
    },

    //查询物品列表
    allRyInventory() {
      allRyInventory().then(response => {
        this.allInventory = response.data;
      });
    },

    /** 查询入库列表 */
    getList() {
      this.loading = true;
      listRyDepotItem(this.queryParams).then(response => {
        this.RyDepotItemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.modificationOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.allPrice = null;
      this.form = {
        id: null,
        headerId: null,
        inventoryId: null,
        operNumber: null,
        allPrice: null,
        specifications: null,
        brand: null,
        wbs: null,
        unitPrice: null,
        remark: null,
        depotId: null,
        // anotherDepotId: null,
        // headerType: null,
        // lockStatus: "0",
        // taxRate: null,
        // taxMoney: null,
        // taxLastMoney: null,
        // snList: null,
        // batchNumber: null,
        // expirationDate: null,
        // linkId: null,
        // tenantId: null,
        // delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let id = row.id || this.ids
      id = typeof id === "object" ? id[0] : id
      this.modificationOpen = true;
      for (let i = 0; i < this.RyDepotItemList.length; i++) {
        if (this.RyDepotItemList[i].id === id) {
          console.log(this.RyDepotItemList[i])
          this.title = "修改入库";
          this.modificationform = this.RyDepotItemList[i]
        }

      }

    },
    /** 新增的提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
          console.log(valid)
        if (valid) {
          addRyDepotItem(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });

        }
      });
    },
    /*修改的提交按钮*/
    modificationSubmitForm() {
      this.modificationform.beforeNum = this.modificationform.operNumber
      this.modificationform.beforeMoney = this.modificationform.allPrice
      this.modificationform.depotitemId = this.modificationform.id
      console.log(this.modificationform.afterNum)
      if (this.modificationform.afterNum === 0 || this.modificationform.afterNum === undefined || this.modificationform.afterNum === '') {
        this.$modal.msgWarning("修改后的入库数量不能0");
      } else {
        updateRyDepotItem(this.modificationform).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.modificationOpen = false;
          this.getList();
        });
      }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库编号为"' + ids + '"的数据项？').then(function () {
        return delRyDepotItem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehouse/RyDepotItem/export', {
        ...this.queryParams
      }, `RyDepotItem_${new Date().getTime()}.xlsx`)
    },
    // handleImportAll() {
    //   this.uploadStatus = true
    //   this.warehouseType = 0
    // },
    // handleImportTool() {
    //   this.uploadStatus = true
    //   this.warehouseType = 1
    // },
    uploadFile(file) {
      let that = this
      const reader = new FileReader()
      reader.readAsArrayBuffer(file.raw)
      reader.onload = function () {
        const buffer = reader.result
        const bytes = new Uint8Array(buffer)
        const length = bytes.byteLength
        let binary = ''
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i])
        }
        const XLSX = require('xlsx')
        const wb = XLSX.read(binary, {
          type: 'binary'
        })
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])

        for (let i = 0; i < outdata.length; i++) {
          let row = {}
          // row.depotId = outdata[i]['仓库id*']
          // row.depotName = outdata[i]['仓库*']
          row.name = outdata[i]['入库物品*']
          row.specifications = outdata[i]['物品规格*']
          row.brand = outdata[i]['品牌']
          row.categoryCode = outdata[i]['品类']
          row.kindCode = outdata[i]['种类']
          row.itemCode = outdata[i]['项']
          row.unitPrice = outdata[i]['单位（元）']
          row.totalNumber = outdata[i]['入库数量*']
          row.remark = outdata[i]['备注']
          that.importData.push(row)
        }
        console.log(that.importData)
     //   that.handleImport1(importData)
      }
    },
    // 导入解析
    handleImport1() {
      let that = this
      return request({
        url: '/warehouse/RyDepotItem/dataImport',
        method: 'post',
        data: {warehouseType: this.warehouseType, dataList: this.importData}
      }).then(response => {
        // this.$modal.msgSuccess(response.msg);
        that.$message({
          showClose: true,
          message: response.msg,
          type: 'success',
          duration: 0
        })
        this.upload.open = false;
        this.getList();
      });
    },
    /** 导入按钮操作 */
    handleImport(id,name) {
      this.warehouseType = id
      this.upload.name = name
      this.upload.title = "导入" + this.upload.name;
      this.upload.open = true;
      this.importData = []
      this.$refs.upload.clearFiles();
    },
    /** 下载模板操作 */
    importTemplate() {
      //定义表头
      let str = `入库物品*,物品规格*,品牌,品类,种类,项,单价(元),入库数量*,备注\n`;
      str += '接近开关,S-150-24,XXX,YYY,ZZZ,XXX,XXX,10,XXX'
      let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
      //通过创建a标签实现
      let link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download = `${this.upload.name+'模板' || '表格数据'}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}
</style>
